function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}

layui.config({
    base: '../js/layui/lay/modules/' //此处路径请自行处理, 可以使用绝对路径
}).extend({
    formSelects: 'formSelects-v4'
});
layui.use(['form','formSelects','layer'], function () {

    var $ = layui.$, form = layui.form, formSelects = layui.formSelects, layer=layui.layer;

    var id = '';


    $(function () {
        LoginStatus();

        id = getUrlParam('id');

        if (id == null || id == '') {
            $('#id').val(id);

            initForm(null);
        } else {
            loadPositionInfo();
        }

    })


    form.on('submit(btnSave)', function (data) {
        data.field.skillRequirement = formSelects.value('skillRequirement', 'valStr');
        data.field.city = formSelects.value('expectCity', 'valStr');

        layer.load(2);

        var method = 'put';
        if (data.field.id != null && data.field.id != '' && data.field.id != 'undefined') {
            method = 'post';
        }

        $.ajax({
            type: method, // 提交方式 get/post
            url: companyServices+"/position", // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:JSON.stringify(data.field),
            success: function(res) {
                layer.closeAll('loading');
                checkLoginStatus(res);
                if(res.status == '00200'){
                    layerMsg(res.message);
                    setTimeout(function() {
                        window.location.href="job-manage.html" ;
                    }, 2000);

                }else{
                    layerMsg(res.message)
                }
            },fail:function () {
                layer.closeAll('loading');
            }
        })
        return false;
    });


    //加载职位列表
    function loadPositionInfo() {
        layer.load(2);
        $.ajax({
            type: 'get', // 提交方式 get/post
            url: companyServices+"/position/" + id, // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:{},
            success: function(res) {
                layer.closeAll('loading');
                checkLoginStatus(res);
                initForm(res.data.position);
            }, fail:function () {
                layer.closeAll('loading');
            }
        })
    }

    $('#delPosition').click(function () {
        layer.confirm('是否确认删除该职位？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            var id = $('#id').val();
            delPosition(id);
        }, function(){

        });

    })

    function delPosition(positionId) {
        var ids = [];
        ids.push(positionId);

        layer.load(2);
        $.ajax({
            type: 'delete', // 提交方式 get/post
            url: companyServices+"/position", // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data: {"ids":ids.join(",")}
            ,success: function(res) {
                layer.closeAll('loading');
                if(res.status == '00200'){
                    layerMsg(res.message);
                    setTimeout(function() {
                        window.location.href="job-manage.html" ;
                    }, 2000);

                }else{
                    layerMsg(res.message)
                }
            },fail:function () {
                layer.closeAll('loading');
            }
        })
    }
    function initForm(obj) {
        if (obj != null) {
            $('#id').val(obj.id);
            $('#positionName').val(obj.positionName);
            $('#workAddress').val(obj.workAddress);
            $('#recruitNumber').val(obj.recruitNumber);
            $('#workDescription').val(obj.workDescription);

            $('#otherSkillRequirement').val(obj.otherSkillRequirement);
            $('#otherWorkAddress').val(obj.otherWorkAddress);
            $('#ageRequirement').val(obj.ageRequirement);

            //重置薪酬范围
            loadSalaryLevel(obj.salaryLevel);
            //重置城市
            loadCity(obj.workCityId);
            //重置工作经验
            loadWorkExperienceLevel(obj.workExperienceLevel);
            //重置学历
            loadEducationLevel(obj.educationLevel);
            //重置年龄
            //loadAgeLevel(obj.ageLevel);
            //重置技能
            loadSkillRequirement(obj.skillRequirement)

            $('#delPosition').show();
        } else {
            $('#id').val('');
            $('#positionName').val('');
            //$('#workAddress').val('');
            $('#recruitNumber').val('');
            $('#workDescription').val('');

            $('#workAddress').val('');
            $('#otherSkillRequirement').val('');
            $('#otherWorkAddress').val('');
            $('#ageRequirement').val('');

            //重置薪酬范围
            loadSalaryLevel(null);
            //重置城市
            loadCity(null);
            //重置工作经验
            loadWorkExperienceLevel(null);
            //重置学历
            loadEducationLevel(null);
            //重置年龄
            //loadAgeLevel(null);
            //重置技能
            loadSkillRequirement(null)

            $('#delPosition').hide();
        }
    }


    //加载薪酬范围
    function loadSalaryLevel(selectId) {
        loadSelectData('salaryLevel', selectId, "/prop/salaryLevel/list?page=1&limit=200");
    }

    function loadSkillRequirement(selectId) {
        $.ajax({
            type: 'get', // 提交方式 get/post
            url: companyServices+"/prop/skill/list?page=1&limit=200", // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:{},
            success: function(res) {
                checkLoginStatus(res);
                formSelects.data('skillRequirement', 'local', {
                    arr:JSON.parse(res).data,
                    keyName:'skillName',
                    keyVal:'id'
                });

                if (selectId != null) {
                    formSelects.value('skillRequirement', selectId.split(','));
                }
            }
        })
    }

    //加载城市
    function loadCity(selectId) {
        layui.use(['treeSelect','form','layer'], function () {
            var treeSelect= layui.treeSelect;

            treeSelect.render({
                // 选择器
                elem: '#expectCity',
                // 数据
                data: companyServices+"/prop/city/tree",
                // 异步加载方式：get/post，默认get
                type: 'get',
                // 占位符
                placeholder: '请选择城市',
                // 是否开启搜索功能：true/false，默认false
                search: false,
                // 点击回调
                click: function(d){
                    $("input[name='workCityId']").val(d.current.value)
                },
                // 加载完成后的回调函数
                success: function (d) {
                    if(selectId){
                        // console.log("selectId:"+typeof(selectId))
                        treeSelect.checkNode('tree', selectId);
                        $("input[name='workCityId']").val(selectId)
                    }
                
                }
            });
        });
        // $.ajax({
        //     type: 'get', // 提交方式 get/post
        //     url: companyServices+"/prop/city/tree", // 需要提交的 url
        //     contentType:"application/json;charset=utf-8",
        //     xhrFields: {
        //         withCredentials: true
        //     }
        //     ,crossDomain: true
        //     ,data:{},
        //     success: function(res) {
        //         checkLoginStatus(res);
        //         formSelects.data('expectCity', 'local', {
        //             arr:JSON.parse(res).data
        //         });

        //         if (selectId != null) {
        //             formSelects.value('expectCity', selectId.split(','));
        //         }
        //     }
        // })
    }

    //加载经验列表
    function loadWorkExperienceLevel(selectId) {
        loadSelectData('workExperienceLevel', selectId, "/prop/workExperienceLevel/list?page=1&limit=200");
    }

    //加载加载年龄列表
    function loadAgeLevel(selectId) {
        loadSelectData('ageLevel', selectId, "/prop/ageLevel/list?page=1&limit=200");
    }

    //加载学历层级
    function loadEducationLevel(selectId) {
        loadSelectData('educationLevel', selectId, "/prop/educationLevel/list?page=1&limit=200");
    }
    //加载下拉选项并选中，如果selectId存在并且相等
    function loadSelectData(selectName, selectId, url) {

        var html = '<option value="">请选择</option>';

        $.ajax({
            type: 'get', // 提交方式 get/post
            url: companyServices+url, // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:{},
            success: function(res) {
                //checkLoginStatus(res);
                if (JSON.parse(res).data != null) {
                    $.each(JSON.parse(res).data, function (index, item) {
                        if (selectId != null && selectId != '' && selectId == item.id) {
                            html += '<option value="'+item.id+'" selected>'+item.name+'</option>';
                        } else {
                            html += '<option value="'+item.id+'">'+item.name+'</option>';
                        }
                    })
                    $('#' + selectName).html(html);
                    form.render();
                }
            }
        })
    }

});




